package p2p.logic.connection.communication.type;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import p2p.logic.connection.communication.AbstractCommunicationHandler;
import p2p.logic.connection.communication.Communication;
import p2p.logic.connection.communication.message.Message;
import p2p.logic.connection.communication.message.MessageSplitter;

/**
 * 
 * Send - Concrete implementation of Communication responsible 
 * for sending an Message  
 */
public class Send extends Communication{
	

	private MessageSplitter splitter;
	private Message message;
	
	public Send(AbstractCommunicationHandler handler){
		super(handler);
	}
	
	public Send(Message message){
		
		try {
			
			this.socket = new DatagramSocket();
		
		} catch (SocketException e) {
			e.printStackTrace();
		}
		

		this.splitter = new MessageSplitter();
		this.message = message;
		
	}
	public Send(AbstractCommunicationHandler handler, Message message) {
		super(handler);
		try {
						
			this.socket = new DatagramSocket();
		
		} catch (SocketException e) {
			e.printStackTrace();
		}
		

		this.splitter = new MessageSplitter();
		this.message = message;
		
	}
	

	@Override
	public void start() {
		
		try {
			
			byte[] send = new byte[1024];
			
			for (Message m : this.splitter.splitMessage(message)){
				
				send = m.getPayload();
				
				DatagramPacket packet = new DatagramPacket(send, send.length, InetAddress.getByName(m.getRecipientIp()), m.getRecipientPort());
						
				this.socket.send(packet);
				
				if (this.handler != null)
					this.handler.handleSendedMessage(new Message(send));
				
			}
		} catch (SocketException e) {

		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	

}
